package mse.eai.esb;

import javax.ejb.Local;
import javax.ejb.Stateless;
import javax.naming.Context;
import javax.naming.InitialContext;

import org.jboss.logging.Logger;
import org.jboss.soa.esb.actions.BeanConfiguredAction;
import org.jboss.soa.esb.message.Message;

import api.PhasebookToken;
import api.ejb.IAuthenticator;

@Stateless(name = "CallAuthenticatorBean")
@Local
public class CallAuthenticatorBean implements BeanConfiguredAction {

	IAuthenticator authenticator;

	private static final Logger log = Logger
			.getLogger(CallAuthenticatorBean.class);

	public Message process(Message message) {
		log.info("ESB Action start ------>");

		try {

			log.info("Authenticating message");

			Context context = new InitialContext();
			authenticator = (IAuthenticator) context
					.lookup("PhaseBook/IAuthenticator/local");

			int userId;
			int appId;
			String tokenId = null;
			try {
				userId = (Integer) message.getBody().get("uid");
				appId = (Integer) message.getBody().get("appId");
				tokenId = (String) message.getBody().get("tokenId");
			} catch (Exception exc) {
				log.info("Auth fields not found or smth..., TOKEN NOT VALIDATED >>>>>>>>>>>>>>><");
				log.info("<------- ESB Action done");
				return null;
			}

			PhasebookToken token = new PhasebookToken();
			token.setAppId(appId);
			token.setToken(tokenId);
			token.setUserId(userId);

			if (!authenticator.validateAuthenticationToken(tokenId)) {
				log.info("\n\n>>>>>>>>>>>>>>>> TOKEN NOT VALIDATED >>>>>>>>>>>>>>>>>>>>>\n\n");
				log.info("<------- ESB Action done");
				return null; // This is the way to stop actions pipeline
			}

			log.info("Message Authenticated");

		} catch (Exception e) {
			log.error("Smth went wrong, so no authentication", e);
			log.info("<------- ESB Action done");
			return null;
		}

		log.info("<------- ESB Action done");
		return message;

	}
}
